﻿using System;
using System.Collections.Generic;
using VXCompany.SilverlightLogging.Services.Exceptions;
using VXCompany.SilverlightLogging.Services.ServiceContracts;

namespace VXCompany.SilverlightLogging.Services.Business
{
	public class LoggingProvider : ILoggingService
	{
		#region Fields

		private static LoggingConfigurationMessage _config;

		#endregion Fields

		#region Constructors

		/// <summary>
		/// Type initialiser. Read configsection.
		/// </summary>
		public LoggingProvider()
		{
			if (_config == null)
			{
				_config = (LoggingConfigurationMessage)System.Web.Configuration.WebConfigurationManager.GetSection("ClientLogging");
				if (_config == null)
				{
					throw new ServiceException("Web.config section 'ClientLogging' was not found.");
				}
			}
		}

		#endregion Constructors

		#region Methods

		/// <summary>
		/// Returns configuration of log and sync levels for client applications.
		/// </summary>
		/// <returns></returns>
		public LoggingConfigurationMessage GetClientConfig()
		{
			LoggingConfigurationMessage conf = null;
			try
			{
				string ip = System.Web.HttpContext.Current.Request.IsLocal ? "localhost" : System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
				bool isAuthenticated = System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated;
				string userid = isAuthenticated ? System.Threading.Thread.CurrentPrincipal.Identity.Name : "anonymous";
				conf = _config.Clone();
				conf.ClientAddress = ip;
				conf.UserID = userid;
				return conf;
			}
			catch (Exception ex)
			{
				throw new ServiceException("Technical error while getting client configuration settings.", ex);
			}
		}

		/// <summary>
		/// Attempts to map exception messages to exceptions, and log them using ExceptionPolicy.
		/// </summary>
		/// <param name="messages">The exception messages from the client, to log here.</param>				
		public void LogExceptionBatch(List<ExceptionMessage> messages)
		{
			bool success = false;
			if (messages == null)
			{
				success = true;
			}
			else
			{
				try
				{
					foreach (var message in messages)
					{
						ClientException ce = ClientExceptionMapper.MapMessageToException(message);
						ExceptionPolicy.Current.HandleException(ce);
					}
					success = true;
				}
				catch
				{
					success = false;
				}
			}
		}


		#endregion Methods
	}
}